package org.swingplus.core.scanner;

import org.swingplus.core.annotation.Autowired;
import org.swingplus.core.annotation.bean.Scope;
import org.swingplus.core.constant.bean.ScopeConstant;
import org.swingplus.core.context.ApplicationContext;
import org.swingplus.core.factory.WidgetFactroy;
import org.swingplus.core.util.AnnoManageUtil;
import org.swingplus.core.util.PropertyManageUtil;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LayoutScan {
	
	
	private static final Logger logger= LoggerFactory.getLogger(LayoutScan.class);
	

//    private static Object Object object;

	public static Annotation[] layoutScan(String packageName,Class<?> clazz){
//    	AnnoManageUtil.getAnnotationType("",clazz);
        Annotation[] annotations1 =null;
        //System.out.println(annotations[0].annotationType().getName());
        Map<String, Object> createByAnnotationType = AnnoManageUtil.createByAnnotationType("",clazz);
        for (String key : createByAnnotationType.keySet()) {
        	Object object = createByAnnotationType.get(key);
        	
        	Map<Field,Annotation[]> annotationsType =AnnoManageUtil.fieldByAnnotationsType(object,Autowired.class);
        	for (Entry<Field, Annotation[]> annotation : annotationsType.entrySet()) {
        		Field field=annotation.getKey();
        		Annotation[] annotations=annotation.getValue();
        		
        		for (int i = 0; i < annotations.length; i++) {
					if(annotations[i].annotationType().getSimpleName().equals("Autowired")) {
						Scope scope = field.getClass().getAnnotation(Scope.class);
						
						logger.info("field[name: {},type: {},Class :{}]",field.getName(),field.getType().getName(),field.getClass().getName());
			        	Object obj= null;
			        	if(scope!=null) {
			        		obj=ApplicationContext.getBean(field.getType().getName(),field.getName(),scope.value());
			        	}else {
			        		obj=ApplicationContext.getBean(field.getType().getName(),field.getName(),ScopeConstant.singleton);
			        	}
//						obj=ApplicationContext.getBean(field.getName());
						if(null==obj) {
							System.out.println("container not exists bean :"+field.getName());
							logger.info("container not exists bean: {}",field.getName());
						}
						try {
							PropertyManageUtil.setProperty(object, field, obj);
						} catch (NoSuchFieldException | SecurityException | IllegalArgumentException
								| IllegalAccessException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
//        	AnnoManageUtil.getAnnotationType("",clazz);
        	ApplicationContext.setBean(key,object);
		}
        return annotations1;

    }

}
